<?php
/**
* 微信登录
*/
class Login extends MY_Controller
{
	
	function __construct()
	{
		parent::__construct();
		//加载微信接口模型
		$this->load->model('WeixinLogin_model','wxLogin');
        $this->load->model('User_model','user');
	}

    /**
	 * 用户登录入口
	 * @param  [type] $shop_token [description]
	 * @return [type]             [description]
	 */
	function index(){
        // $data['title'] = '用户注册';
        // $this->load->view('weixin/common/header',$data);
        // $this->load->view('weixin/login/register');
        //header跳转获取code
		$this->wxLogin->header();
	}

 
    /**
     * @abstract 静默状态访问回调
     */
    public function weixinLoginBack(){
        
        $code = $_GET['code'];
        $user_info = $this->wxLogin->getUserByCode($code);
        //$user_info = $this->wxLogin->get_user_code($code);

        if(!$user_info){
            //抓取用户信息失败  重试
            redirect(base_url().'Weixin/Login/index');
        }
       
        //检测是否存在该用户
        $where = array(
        	'openid'    => $user_info['openid'],
        );
        $check_user = $this->user->getUser($where);
        if($check_user != NULL){
            //如果存在该用户
            $_SESSION['userinfo'] = $check_user;
            
        }else{
            //如果不存在该用户，session保存用户信息 进入欢迎页
            
            $_SESSION['userinfo'] = $this->wxLogin($user_info);
        }
        
        redirect($_SESSION['redirect_url']);
    }

    /**
     * @abstract 微信登录 添加用户
     * @return [type] [description]
     */
    function wxLogin($user_info){        
        $data = array(
            'openid'      =>  $user_info['openid'],
            'nickname'    =>  $user_info['nickname'],
            'area'        =>  $user_info['country'].$user_info['province'].$user_info['city'],
            'headimgurl'  =>  $user_info['headimgurl'],
            'sex'         =>  $user_info['sex'],
        );
        $this->user->addUser($data);
        return $data;
    }

}
